package nimo.elibrary.db.model;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import nimo.elibrary.db.DatabaseHelper;

/**
 * Created with IntelliJ IDEA.
 * User: Enkuso
 * Date: 12/11/12
 * Time: 12:53 PM
 * To change this template use File | Settings | File Templates.
 */
public class UserDataSource {

    // Database fields
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;
    private String[] allcolumns = { DatabaseHelper.COLUMN_ID,
        DatabaseHelper.COLUMN_USERNAME,
        DatabaseHelper.COLUMN_USEREMAIL,
        DatabaseHelper.COLUMN_USERPWD,
        DatabaseHelper.COLUMN_USERTOKEN,
        DatabaseHelper.COLUMN_USERFNAME,
        DatabaseHelper.COLUMN_USERLNAME };

    public UserDataSource(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    public void open() throws SQLiteException {
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }

    public User createUser(String username, String email, String password, String token, String fname, String lname) {

        // insert user data local Database
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_USERNAME, username);
        values.put(DatabaseHelper.COLUMN_USEREMAIL, email);
        values.put(DatabaseHelper.COLUMN_USERPWD, password);
        values.put(DatabaseHelper.COLUMN_USERTOKEN, token);
        values.put(DatabaseHelper.COLUMN_USERFNAME, fname);
        values.put(DatabaseHelper.COLUMN_USERLNAME, lname);
        long insertId = database.insert(DatabaseHelper.TABLE_USER, null, values);
        Cursor cursor = database.query(DatabaseHelper.TABLE_USER,
                allcolumns, DatabaseHelper.COLUMN_ID + " = " + insertId, null,
                null, null, null);
        cursor.moveToFirst();
        User newUser = cursorToUser(cursor);
        cursor.close();

        return newUser;
    }

    public User createOrUpdateUser(String username, String email, String password, String token, String fname, String lname) {

        Cursor chk = database.query(DatabaseHelper.TABLE_USER, allcolumns, DatabaseHelper.COLUMN_USERNAME + " = ?", new String[] {username}, null, null, null);
        if(chk != null && chk.getCount() > 0){
            updateUserToken(username, token);
            chk.moveToFirst();
            User existingUser = cursorToUser(chk);
            chk.close();

            return existingUser;
        }
        else {
            // insert user data local Database
            ContentValues values = new ContentValues();
            values.put(DatabaseHelper.COLUMN_USERNAME, username);
            values.put(DatabaseHelper.COLUMN_USEREMAIL, email);
            values.put(DatabaseHelper.COLUMN_USERPWD, password);
            values.put(DatabaseHelper.COLUMN_USERTOKEN, token);
            values.put(DatabaseHelper.COLUMN_USERFNAME, fname);
            values.put(DatabaseHelper.COLUMN_USERLNAME, lname);
            long insertId = database.insert(DatabaseHelper.TABLE_USER, null, values);
            Cursor cursor = database.query(DatabaseHelper.TABLE_USER,
                    allcolumns, DatabaseHelper.COLUMN_ID + " = " + insertId, null,
                    null, null, null);
            cursor.moveToFirst();
            User newUser = cursorToUser(cursor);
            cursor.close();

            return newUser;
        }
    }

    public User insertUser(User user) {

        // insert user data local Database
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_USERNAME, user.username);
        values.put(DatabaseHelper.COLUMN_USEREMAIL, user.email);
        values.put(DatabaseHelper.COLUMN_USERPWD, user.getPassword());
        values.put(DatabaseHelper.COLUMN_USERTOKEN, user.token);
        values.put(DatabaseHelper.COLUMN_USERFNAME, user.firstName);
        values.put(DatabaseHelper.COLUMN_USERLNAME, user.lastName);
        long insertId = database.insert(DatabaseHelper.TABLE_USER, null, values);
        Cursor cursor = database.query(DatabaseHelper.TABLE_USER,
                allcolumns, DatabaseHelper.COLUMN_ID + " = " + insertId, null,
                null, null, null);
        cursor.moveToFirst();
        User newUser = cursorToUser(cursor);
        cursor.close();

        return newUser;
    }

    public void deleteUser(User user) {
        long id = user.getId();
        database.delete(DatabaseHelper.TABLE_USER, DatabaseHelper.COLUMN_ID + " = " + id, null);
    }

    public User getLoggedUser() {
        Cursor cursor = database.query(DatabaseHelper.TABLE_USER,
                allcolumns, DatabaseHelper.COLUMN_USERTOKEN + " NOT NULL", null,
                null, null, DatabaseHelper.COLUMN_ID + " DESC", "1");
        cursor.moveToFirst();
        User loggedUser = cursorToUser(cursor);
        cursor.close();

        return loggedUser;
    }

    public void removeUserToken(String username) {
        ContentValues values = new ContentValues();
        values.putNull(DatabaseHelper.COLUMN_USERTOKEN);
        database.update(DatabaseHelper.TABLE_USER, values, DatabaseHelper.COLUMN_USERNAME + " = ?", new String[]{username});
    }

    public void updateUserToken(String username, String token) {
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_USERTOKEN, token);
        database.update(DatabaseHelper.TABLE_USER, values, DatabaseHelper.COLUMN_USERNAME + " = ?", new String[]{username});
    }

    private User cursorToUser(Cursor cursor) {
        if(cursor!=null && cursor.getCount()>0) {
            User user = new User();
            user.setId(cursor.getLong(0));
            user.username = cursor.getString(1);
            user.email = cursor.getString(2);
            user.setPassword(cursor.getString(3));
            user.token = cursor.getString(4);
            user.firstName = cursor.getString(5);
            user.lastName = cursor.getString(6);
            return user;
        }
        return null;
    }
}
